using System;
using Microsoft.AspNetCore.Mvc;
using ApiProject.Api.Entity;
using System.Linq;
using ApiProject.Api.Repository;
using Microsoft.Extensions.Configuration;
using ApiProject.Api.Uitls;
using Microsoft.AspNetCore.Hosting;
using ApiProject.Api.Utils;
using ApiProject.Api.PramaModel;
using Microsoft.AspNetCore.Authorization;


// 文章管理
namespace ApiProject.Api.Controllers
{
    [Authorize]
    [ApiController]
    [Route("[controller]")]
    public class ArticleController : ControllerBase
    {
        private IRepository<Articles> _articleRepository;

        private IRepository<ArticleTypes> _articleTypeRepository;

        private readonly IWebHostEnvironment _hostingEnvironment;

        private readonly IConfiguration _configuration;

        public ArticleController(
            IConfiguration configuration,
            IRepository<Articles> articleRepository,
        IRepository<ArticleTypes> articleTypeRepository,
        IWebHostEnvironment hostingEnvironment

        )
        {
            _articleRepository = articleRepository;
            _articleTypeRepository = articleTypeRepository;
            _configuration = configuration;
            _hostingEnvironment = hostingEnvironment;
        }


        //查找已启用的文章类型
        //Get /article/type
        [AllowAnonymous]
        [HttpGet, Route("type")]
        public dynamic Get()
        {
            var allType = _articleTypeRepository.Table.Where(x => x.IsEnable == true).ToList();

            return JsonHelper.Serialize(new
            {
                Code = 200,
                Data = allType
            });
        }


         //通过文章Id查找已经启用的文章
        [HttpGet, Route("ace/{id}")]
        [AllowAnonymous]
        public dynamic GetArticleByIdace(int id)
        {
            var article = _articleRepository.GetById(id);
            if (article != null)
            {
                if (article.IsDelete == false)
                {
                    if (article.IsEnable == true)
                    {
                        return JsonHelper.Serialize(new
                        {
                            Code = 200,
                            Data = article
                        });
                    }
                    else
                    {
                        return JsonHelper.Serialize(new
                        {
                            Code = 1000,
                            Data = "",
                            Msg = "文章已禁用"
                        });
                    }

                }
                else
                {
                    return JsonHelper.Serialize(new
                    {
                        Code = 1000,
                        Data = "",
                        Msg = "文章已删除"
                    });
                }
            }
            else
            {
                return JsonHelper.Serialize(new
                    {
                        Code = 1000,
                        Data = "",
                        Msg = "并没有这篇文章，文章为空"
                    }); 
            }



        }





        // 添加图片
        //Post /article/addpic
        [HttpPost, Route("addpic")]
        public dynamic AddPicture()
        {
            var files = HttpContext.Request.Form.Files;

            string webRootPath = _hostingEnvironment.WebRootPath; // ...Api/wwwroot
            var showfilePath = PicHelper.getFilePath(files, "upload", webRootPath);

            Console.WriteLine(showfilePath);

            return JsonHelper.Serialize(new
            {
                Code = 1000,
                Data = showfilePath,
                Msg = "添加图片成功"
            });
        }


        //删除文章图片
        //Post /article/deletepic
        [HttpPut, Route("deletepic")]
        public dynamic Put(NewArticle model)
        {
            var str = model.PicPath;

            string webRootPath = _hostingEnvironment.WebRootPath; // ...Api/wwwroot

            var picpath = webRootPath + str;

            FileHelper.FileDel(picpath);

            return "Ok";


        }


        //添加文章(先将文字添加创建文章后，返回文章Id，添加封面图)
        // Post /article/add
        [HttpPost, Route("add")]
        public dynamic AddArticle(NewArticle model)
        {

            var articleTitle = model.ArticleTitle;
            var articleExplain = model.ArticleExplain;
            var articleAuthor = model.ArticleAuthor;
            var articleTypeNum = model.ArticleTypeNum;
            // var articleContent = model.ArticleContent;
            var mdContent = model.MdContent;
            var adminName = model.AdminName;

            var article = _articleRepository.Table.Where(x => x.ArticleTitle == articleTitle).FirstOrDefault();

            if (article == null)
            {
                var newArticle = new Articles
                {
                    ArticleTitle = articleTitle,
                    ArticleExplain = articleExplain,
                    ArticleAuthor = articleAuthor,
                    ArticleTypeNum = articleTypeNum,
                    // ArticleContent = articleContent,
                    MdContent = mdContent,
                    IsEnable = false,
                    AdminName = adminName
                };

                _articleRepository.Insert(newArticle);

                var tmp = _articleRepository.Table.Where(x => x.ArticleTitle == articleTitle).FirstOrDefault();

                return JsonHelper.Serialize(new
                {
                    Code = 200,
                    Data = tmp.Id,
                    Msg = "创建文章成功"
                });
            }
            else
            {
                if (article.IsDelete == false)
                {
                    var newArticle = new Articles
                    {
                        ArticleTitle = articleTitle,
                        ArticleExplain = articleExplain,
                        ArticleAuthor = articleAuthor,
                        ArticleTypeNum = articleTypeNum,
                        // ArticleContent = articleContent,
                        MdContent = mdContent,
                        IsEnable = false,
                        AdminName = adminName
                    };

                    _articleRepository.Insert(newArticle);

                    var tmp = _articleRepository.Table.Where(x => x.ArticleTitle == articleTitle).FirstOrDefault();

                    return JsonHelper.Serialize(new
                    {
                        Code = 200,
                        Data = tmp.Id,
                        Msg = "创建文章成功"
                    });
                }
                else
                {
                    return JsonHelper.Serialize(new
                    {
                        Code = 1000,
                        Data = "",
                        Msg = "文章标题重复，请重新填写"
                    });
                }
            }


        }


        // 添加文章封面
        // Put /article/addpicture
        [HttpPut, Route("addpicture")]
        public dynamic AddArticlePic()
        {

            var files = HttpContext.Request.Form.Files;
            var id = Int32.Parse(HttpContext.Request.Form["id"]);

            var article = _articleRepository.GetById(id);

            string webRootPath = _hostingEnvironment.WebRootPath; // ...Api/wwwroot
            var showfilePath = PicHelper.getFilePath(files, "upload", webRootPath);

            if (showfilePath != "")
            {
                article.ArticleSurface = showfilePath;
                article.UpdatedTime = DateTime.Now;

                _articleRepository.Update(article);

                return JsonHelper.Serialize(new
                {
                    Code = 200,
                    Data = showfilePath,
                    Msg = "添加图片成功"
                });
            }
            else
            {
                return JsonHelper.Serialize(new
                {
                    Code = 1000,
                    Data = "",
                    Msg = "添加图片失败"
                });
            }


        }



        // 查询所有未发布文章
        //Get: /article/allnotpublish
        [HttpGet, Route("allnotpublish")]
        public dynamic Get([FromQuery] Pages page)
        {
            var pageIndex = page.pageIndex;
            var pageSize = page.pageSize;
            var articles = _articleRepository.Table.Where(x => x.IsEnable == false && x.IsDelete == false);
            var u = articles.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();

            return JsonHelper.Serialize(new
            {
                Code = 200,
                Data = new { Data = u, pager = new { pageIndex, pageSize, rowsTotal = articles.Count() } },
                Msg = "获取成功"
            });
        }



        // 获取当前文章Id的文章
        // Get /article/getarticle/{id}
        [AllowAnonymous]
        [HttpGet, Route("getarticle/{id}")]
        public dynamic GetArticleById(int id)
        {

            var article = _articleRepository.GetById(id);

            return JsonHelper.Serialize(new
            {
                Code = 200,
                Data = article,
                Msg = "获取成功"
            });
        }



        // 编辑文章封面
        // 添加图片
        //Put /article/updatepic/{id}
        [HttpPut, Route("updatepic/{id}")]
        public dynamic UpdatePicture(int id)
        {
            var files = HttpContext.Request.Form.Files;

            string webRootPath = _hostingEnvironment.WebRootPath; // ...Api/wwwroot
            var showfilePath = PicHelper.getFilePath(files, "upload", webRootPath);

            Console.WriteLine(showfilePath);

            var article = _articleRepository.GetById(id);

            article.ArticleSurface = showfilePath;
            article.UpdatedTime = DateTime.Now;

            _articleRepository.Update(article);


            return JsonHelper.Serialize(new
            {
                Code = 1000,
                Data = showfilePath,
                Msg = "添加图片成功"
            });
        }



        //修改文章
        // Pout /article/update/{id}
        [HttpPut, Route("update/{id}")]
        public dynamic UpdateArticle(int id, NewArticle model)
        {

            var articleTitle = model.ArticleTitle;
            var articleExplain = model.ArticleExplain;
            var articleAuthor = model.ArticleAuthor;
            var articleTypeNum = model.ArticleTypeNum;
            // var articleContent = model.ArticleContent;
            var mdContent = model.MdContent;
            var adminName = "admin";

            var article = _articleRepository.GetById(id);

            article.ArticleTitle = articleTitle;
            article.ArticleExplain = articleExplain;
            article.ArticleAuthor = articleAuthor;
            article.ArticleTypeNum = articleTypeNum;
            // article.ArticleContent = articleContent;
            article.MdContent = mdContent;
            article.AdminName = adminName;


            _articleRepository.Update(article);

            return JsonHelper.Serialize(new
            {
                Code = 200,
                Data = "",
                Msg = "修改文章成功"
            });


        }



        //删除文章封面图片
        //Post /article/deleteartpic
        [HttpPut, Route("deleteartpic")]
        public dynamic Putdelete(NewArticle model)
        {
            var str = model.OldImgeUrl;

            string webRootPath = _hostingEnvironment.WebRootPath; // ...Api/wwwroot

            var picpath = webRootPath + str;

            FileHelper.FileDel(picpath);

            return "Ok";
        }



        // 伪删除文章
        // Post /article/delete/{id}
        [HttpPost, Route("delete/{id}")]
        public dynamic DeleteArticle(int id)
        {

            var article = _articleRepository.GetById(id);

            article.IsDelete = true;
            article.UpdatedTime = DateTime.Now;

            _articleRepository.Update(article);

            return "删除文章成功";
        }

        //点击发布文章
        //Post /article/publish/{id}
        [HttpPost, Route("publish/{id}")]
        public dynamic PublishArticle(int id)
        {

            var article = _articleRepository.GetById(id);

            article.IsEnable = true;
            article.CreatedTime = DateTime.Now;

            _articleRepository.Update(article);

            return "发布文章成功";
        }


        //查找已发布文章
        //Get /article/allpublish
        [HttpGet, Route("allpublish")]
        public dynamic GetPublishArticle([FromQuery] Pages page)
        {
            var pageIndex = page.pageIndex;
            var pageSize = page.pageSize;
            var articles = _articleRepository.Table.Where(x => x.IsEnable == true && x.IsDelete == false);
            var u = articles.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();

            return JsonHelper.Serialize(new
            {
                Code = 200,
                Data = new { Data = u, pager = new { pageIndex, pageSize, rowsTotal = articles.Count() } },
                Msg = "获取成功"
            });
        }



        //编辑是否推荐文章
        //Post /article/isrecommend/{id}
        [HttpPost, Route("isrecommend/{id}")]
        public dynamic IsRecommendArticle(int id, NewArticle model)
        {

            var article = _articleRepository.GetById(id);

            var num = model.IsRecommend;

            if (article != null)
            {
                if (num == false)
                {
                    article.IsRecommend = false;
                    article.UpdatedTime = DateTime.Now;
                    _articleRepository.Update(article);
                    return JsonHelper.Serialize(new
                    {
                        Code = 200,
                        Data = article
                    });
                }
                else
                {
                    article.IsRecommend = true;
                    article.UpdatedTime = DateTime.Now;
                    _articleRepository.Update(article);
                    return JsonHelper.Serialize(new
                    {
                        Code = 200,
                        Data = article
                    });
                }

            }
            else
            {
                return JsonHelper.Serialize(new { Code = 1000, Data = "", Msg = "推荐失败" });
            }


        }


        //撤回发布文章
        //Post /article/cancel/{id}
        [HttpPost, Route("cancel/{id}")]
        public dynamic CancelPublish(int id)
        {

            var article = _articleRepository.GetById(id);

            article.IsEnable = false;
            article.UpdatedTime = DateTime.Now;

            _articleRepository.Update(article);

            return JsonHelper.Serialize(new
            {
                Code = 200,
                Msg = "撤回成功"
            });
        }



        //查找相应id文章的全部内容
        //Get /article/detail/{id}
        [HttpGet, Route("detail/{id}")]
        public dynamic GetArticleDetail(int id)
        {

            var article = from art in _articleRepository.Table
                          join type in _articleTypeRepository.Table on art.ArticleTypeNum equals type.Id
                          where art.Id == id
                          select new
                          {
                              ArticleTitle = art.ArticleTitle,
                              ArticleExplain = art.ArticleExplain,
                              // ArticleContent = art.ArticleContent,
                              MdContent = art.MdContent,
                              ArticleAuthor = art.ArticleAuthor,
                              ArticleSurface = art.ArticleSurface,
                              ArticleType = type.ArticleType
                          };

            return JsonHelper.Serialize(new
            {
                Code = 200,
                Data = article
            });
        }

    }
}